#!/usr/bin/env python
#-*-encoding:utf-8-*-
'''
Created on 2015年3月24日

@author: chenyongbing
'''
import sys,os,re
#current_dir = os.path.dirname(__file__)
current_dir = os.path.split(os.path.realpath(__file__))[0]

import os,sys,argparse
import time
import datetime
import commands
import logging



from logging.handlers import RotatingFileHandler

level = logging.INFO

Rthandler = RotatingFileHandler('/var/log/pydellog.log', maxBytes=10*1024*1024,backupCount=0)
Rthandler.setLevel(level)
formatter = logging.Formatter('%(asctime)s - %(name)s - %(levelname)s - %(message)s')
Rthandler.setFormatter(formatter)
logging.getLogger('').addHandler(Rthandler)

console = logging.StreamHandler()
console.setLevel(level)
console.setFormatter(formatter)
logging.getLogger('').addHandler(console)


# FORMAT = '%(asctime)s - %(name)s - %(levelname)s - %(message)s'
# logging.basicConfig(filename='/var/log/pydellog.log',format=FORMAT,)
# logging.basicConfig(level=logging.DEBUG)
# logger = logging.getLogger('dellog')

class gzipZmLogs(object):
    '''
    classdocs
    '''



    def __init__(self,gzipDir='/usr/java/',suffix=None,prefix=None,gzipCycle=7,testing=False):
        '''
        Constructor
        '''
        self.suffix = suffix
        self.prefix = prefix
        self.gzipDir = gzipDir
        self.gzipCycle = gzipCycle
        self.testing = testing
        if self.testing:
            logging.warn('Testing .....')
      
    
    def gzipLog(self):
        today = datetime.date.today().strftime('%Y-%m-%d')
        delday = (datetime.date.today()-datetime.timedelta(int(self.gzipCycle))).strftime('%Y-%m-%d')
        
        
        gzipCount = 0
        errCount = 0
        logPath = self.gzipDir
        if not os.path.exists(logPath):
            logging.warn( 'WARNING - gzip Log Path Not Exists.')
            
            sys.exit(1)
        gzipLogs = os.listdir(logPath)
        os.chdir(logPath)
        
        for gzipLog in gzipLogs:
            if self.suffix!=None and  not re.search('%s$'%self.suffix,gzipLog):
                logging.warn('file %s not match suffix %s'%(gzipLog,self.suffix))
                continue
            if self.prefix!=None and not re.search('^%s'%self.prefix,gzipLog):
                logging.warn('file %s not match prefix %s'%(gzipLog,self.prefix))
                continue
            
            mtime = time.strftime("%Y-%m-%d",time.localtime(os.stat(logPath+'/'+gzipLog).st_mtime))
            if mtime > delday:
                logging.warn('file %s mtime %s'%(gzipLog,mtime))
                continue
            cmd = 'gzip %s'%(gzipLog)
            if self.testing:
                logging.warn('file %s mtime %s del.'%(gzipLog,mtime))
                gzipCount+=1
            else:
                out = commands.getstatusoutput(cmd)
                if int(out[0])==0:
                    gzipCount+=1
                    logging.info('gzip file %s successful.'%gzipLog)
                else:
                    errCount+=1
                    logging.error('gzip file %s faild.'%gzipLog)
        if errCount!=0:
            logging.ERROR('gzip Faild %s , Success %s'%(errCount,gzipCount))
            sys.exit(2)
        elif gzipCount!=0:
            logging.warn('gzip Success %s'%(gzipCount))
            sys.exit(0)
        else:
            logging.warn('no file must be gzip.')
            sys.exit(0)
        
if __name__ == '__main__':
    parser = argparse.ArgumentParser(description='args')
    parser.add_argument('--dir',metavar="需要gzip的目录",required=True)
    parser.add_argument('--suffix',metavar="文件后缀",default=None)
    parser.add_argument('--prefix',metavar="文件前缀",default=None)
    parser.add_argument('--cycle',metavar="gzip周期，默认7天前",default=1,type=int)
    parser.add_argument('--testing',action='store_true',help='testing')
  
    args = parser.parse_args()
    gzipDir = args.dir
    suffix = args.suffix
    prefix = args.prefix
    testing = args.testing
    gzipCycle = args.cycle
 
    
    myDelZmLogs = gzipZmLogs(gzipDir,suffix=suffix,prefix=prefix,gzipCycle=gzipCycle,testing=testing)
    myDelZmLogs.gzipLog()